package io.github.bigbird0101.yousishi.sql.print;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;
import java.util.Arrays;
import java.util.List;

/**
 * Main
 *
 * @author m15179835326@163.com
 * @date 2022/01/19 11:21
 * @description
 * @since 1.0.0
 */
public class Main {
    private static final List<PrintSql> PRINT_SQL_LIST = Arrays.asList(new PgAdapter(), new H2Adapter(),
            new NewMySqlAdapter(), new OldMysqlAdapter());


    public static void premain(String args, Instrumentation instrumentation) {
        boolean isFormatSql = null == args || args.contains("isFormatSql=true");
        instrumentation.addTransformer(new ClassFileTransformer() {
            @Override
            public byte[] transform(ClassLoader loader,
                                    String className,
                                    Class<?> classBeingRedefined,
                                    ProtectionDomain protectionDomain,
                                    byte[] classfileBuffer) {
                for(PrintSql printSql:PRINT_SQL_LIST){
                    if(printSql.match(className)){
                        return printSql.doPrintSqlClass(loader,isFormatSql);
                    }
                }
                return null;
            }
        });
    }

    public static void agentmain(String agentArgs, Instrumentation inst) {
    }
}
